package com.xyzwps.paimon.furina.modules.post.service

import com.xyzwps.paimon.furina.common.AppErrorCode.*
import com.xyzwps.paimon.furina.common.AppException
import com.xyzwps.paimon.furina.common.DateTimeUtil
import com.xyzwps.paimon.furina.common.value.DedupKey
import com.xyzwps.paimon.furina.modules.post.entity.Post
import com.xyzwps.paimon.furina.modules.post.entity.PostRepository
import com.xyzwps.paimon.furina.modules.post.entity.PostType
import org.springframework.stereotype.Service

@Service
class PostService(
    private val postRepository: PostRepository,
    private val collectionService: PostCollectionService
) {

    fun create(
        currentUserId: Long,
        collectionId: Long,
        title: String,
        type: PostType,
        content: String,
        tagIds: List<Long>,
        dedupKey: DedupKey
    ): Post {
        collectionService.findById(collectionId, currentUserId) ?: throw AppException(POST_COLLECTION_NOT_FOUND)
        return postRepository.create(currentUserId, collectionId, title, type, content, tagIds, dedupKey)
            ?: throw AppException(UNHANDLED, "DedupKey 生成算法有问题？")
    }

    fun update(id: Long, currentUserId: Long, title: String, type: PostType, content: String, tagIds: List<Long>): Post {
        val post = findById(id, currentUserId) ?: throw AppException(POST_NOT_FOUND)

        val updatedPost = post.copy(
            title = title, type = type, content = content, tagIds = tagIds,
            updateTime = DateTimeUtil.currentLocalDateTime()
        )
        postRepository.update(updatedPost)
        return updatedPost
    }

    fun delete(id: Long, currentUserId: Long): Boolean {
        val post = findById(id, currentUserId) ?: return false

        val now = DateTimeUtil.currentLocalDateTime()
        val deletedPost = post.copy(deleteTime = now, updateTime = now)
        postRepository.update(deletedPost)
        return true
    }

    fun deleteByCollectionId(collectionId: Long, userId: Long) {
        postRepository.deleteByCollectionId(collectionId, userId)
    }

    fun findById(id: Long, currentUserId: Long): Post? {
        return postRepository.findById(id)
            ?.takeIf { it.userId == currentUserId }
    }

    fun findById(id: Long): Post? = postRepository.findById(id)

    fun findByCollectionId(collectionId: Long, currentUserId: Long): List<Post> {
        collectionService.findById(collectionId, currentUserId) ?: return listOf()
        return postRepository.findByCollectionId(collectionId).filter { it.userId == currentUserId }
    }

    fun findByCollectionId(collectionId: Long): List<Post> {
        collectionService.findById(collectionId) ?: return listOf()
        return postRepository.findByCollectionId(collectionId)
    }
}